<template>
  <div
    v-if="!initializing"
    v-resize="resize"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  >
    <div ref="chartDiv" class="vc-echarts-pie" :style="style"></div>
  </div>
  <div
    v-else
    v-loading="true"
    element-loading-text=""
    style="min-height: 30px;"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  ></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, inject, getCurrentInstance, markRaw, nextTick } from 'vue';
import * as echarts from "echarts";
import visual from "@/visual/js/visual";
import EventHandler from "@/visual/js/event";
import * as chart from "@/visual/js/echarts";
import JSON5 from 'json5';
import { parseColors } from "@/utils/color";
import tool from "@/utils/tool";

const props = defineProps({
  node: Object
});

const chartDiv = ref();
const currChart = ref(null);
const initializing = ref(true);
const currNode = ref(props.node);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  await nextTick(() => initializing.value = false);
};

const loadData = tool.debounce(async() => {
  if (!chartDiv.value) return;
  const compStyle = currNode.value.currCompStyle || {};
  const compData = currNode.value.compData || {};
  const defaultOption = JSON5.parse(compStyle['jsonOption'] || '{}');
  const dataList = (await visual.loadData(
    compData,
    eventHandler,
    getData(),
    currNode.value)).data || [];

  let seriesData = [];
  dataList.forEach(data => {
    seriesData.push({
      name: data['标签'] || data['标题'],
      value: data['系列'] || data['数值']
    });
  });

  const option = {
    animation: compStyle['animation'] || false,
    color: parseColors(compStyle['colorScheme']),
    title: chart.parseTitle(compStyle),
    tooltip: chart.parseTooltip(compStyle),
    legend: chart.parseLegend(compStyle),
    series: [
      {
        ...parsePie(compStyle),
        data: seriesData
      }
    ],
    toolbox: chart.parseToolbox(compStyle)
  };

  await nextTick(() => {
    if (!chartDiv.value) return;
    if (currChart.value) currChart.value.dispose();
    currChart.value = markRaw(echarts.init(chartDiv.value));
    currChart.value.setOption(Object.assign({}, option, defaultOption));
    currChart.value.on('click', 'series', function (params) {
      const data = {
        '标签': params.name,
        '系列': params.value,
        '系列值': params.value
      };
      eventHandler.trigger("点击数据项事件", data);
    });
  });
  resize();
});

const parsePie = (compStyle) => {
  const result = { type: 'pie' };

  if (compStyle['series.padAngle']) {
    result['padAngle'] = compStyle['series.padAngle'];
  }

  if (compStyle['series.radius']) {
    result['radius'] = compStyle['series.radius'].split(',');
  }

  if (compStyle['series.borderRadius']) {
    result['itemStyle'] = {
      borderRadius: compStyle['series.borderRadius'].split(',')
    };
  }

  if (compStyle['series.rose']) {
    result['roseType'] = compStyle['series.roseType'];
  }

  if (compStyle['series.formatter']) {
    result['label'] = {
      formatter: compStyle['series.formatter'],
      color: 'inherit'
    }
  }

  return result;
};

const style = computed(() => {
  const compStyle = currNode.value.currCompStyle || {};

  let result = '';
  result += visual.parseTpl('width: {value};', compStyle['width']);
  result += visual.parseTpl('height: {value};', compStyle['height']);
  return result;
});

const getData = () => {
  return { inputParam: currNode.value.inputParam || {} };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = async() => {
  await init();
  loadData();
};

const resize = () => {
  try {
    currChart.value.resize();
  } catch (e) {
    console.log(e);
  }
};

onMounted(async() => {
  await init();
  loadData();
});

onUnmounted(() => {
  eventHandler.unregister();
});

defineExpose({ getData, changeStyle, refresh, loadData });
</script>